//select inventory less than value
var lzInventory = "";

var curifUniformSpec="";
//订单列表实例
var $table = $("#sku_list_table");
//当前产品线
var sourceType;

var curEditId;
//refer to Java Arraylist blah modCount
var modCount = {};

//编辑sku图url
var editThumbUrl = "";

//dropzone instance
var goodsThumbDropzone;

//跳转过来的找某个商品的sku
var goodsId;

$(function () {
    goodsId=getvl("goodsId");
    initSkuTable($table);
    initDropzone();
});

function initDropzone() {
    Dropzone.autoDiscover = false;//解决两次实例Dropzone错误，可在控制台看到该错误
    //sku图修改
    goodsThumbDropzone = new Dropzone("div#editThumbPic",
        {
            url: urlcore + "/api/attachment/upload",
//                                        paramName: "skuUrl", // The name that will be used to transfer the file
            maxFiles: 1,
            thumbnailWidth: 120,
            thumbnailHeight: 120,
            addRemoveLinks: true,//清除图片
            dictRemoveFile: "删除图片",//如果addRemoveLinks为 true，这段文本用来设置删除文件显示文本.
            dictCancelUpload: "取消上传",//如果addRemoveLinks为 true，这段文本用来设置取消上载链接的文本
            dictMaxFilesExceeded: "上传数量已达上限",
            previewsContainer: "#editThumbPic-pre", // 文件预览显示位置,可以为id或class选择器或html元素
            success: function (file, data) {
                //这里的$(this)其实得到的是Dropzone对象（对象数组，取第一个为当前Dropzone对象）
                console.log($(this));
                //通过查看Dropzone对象的结构得到对应div的id
                console.log("file:", file);
                console.log("data:", data);
                editThumbUrl = data.data[0];
                //重要！！为file对象添加一个url属性，将上传完成的图片url加到该属性值中，之后的removeFile和从待上传url数组中删除都依赖这个操作
                file.url = editThumbUrl;
                console.log(file);
                //放进数组中
            },
            init: function () {
                this.on("addedfile", function (file) {
                    console.log("addedfile");// actions...
                    /*        file.previewElement.addEventListener("click", function () {
                                goodsThumbDropzone.removeFile(file);
                            });*/

                });
                this.on("maxfilesexceeded", function (file) {
                    if (editThumbUrl != "") {
                        goodsThumbDropzone.removeFile(file);
                        alert("已达上传数量上限");
                    }
                });
                this.on("removedfile", function (file) {
                    if (file.url != undefined && file.url == editThumbUrl) {
                        editThumbUrl = "";
                    }
                    //从数组中移除url,因移除的file必然先存在，所以无需判断indexOf为-1
                    console.log("removedfile", file);// actions...
                });
            }
        });

}

//更换产品线
$("#groupType").on("change", function () {
    var temp = $("#groupType").val();
    sourceType = temp;
    $table.bootstrapTable('refresh');
});

//更换筛选订单状态
$("#inventory").on("change", function () {
    var temp = $("#inventory").val();
    lzInventory = temp;
    $table.bootstrapTable('refresh');
});

//更换筛选订单状态
$("#curifUniformSpec").on("change", function () {
    var temp = $("#curifUniformSpec").val();
    curifUniformSpec = temp;
    $table.bootstrapTable('refresh');
});


var columns = [{
        title: "序号",
        align: "center",
        valign: "middle",
        width: "50px",
        formatter: function (value, row, index) {
            return (index + 1);
        }
    }, {
        field: "id",
        title: "规格ID",
        halign: "center",
        valign: "middle",
        align: "center",
        width: "80px"
    }, {
        field: "goods",
        title: "商品名称",
        valign: "middle",
        halign: "center",
        width: "306px",
        sortable: true,
        formatter: function (value, row, index) {
            return value.goodsName;
        }
    },{
        field: "goods",
        title: "商品标价",
        valign: "middle",
        halign: "center",
        width: "70px",
        sortable: true,
        formatter: function (value, row, index) {
            return value.mPrice;
        }
    },{
        field: "ifUniformSpec",
        title: "规格",
        halign: "center",
        valign: "middle",
        width: "80px",
        sortable: true,
        formatter: function (value, row, index) {
            value = (value == 1 ? "多规格" : "统一规格");
            return value;
        }
    }, {
        field: "valuesStr",
        title: "规格名称",
        halign: "center",
        valign: "middle",
        align: "center",
        width: "80px",
        formatter: function (value, row, index) {
            value = (value == null ? "" : value);
            return value;
        }
    }, {
        field: "skuUrl",
        title: "规格图片",
        halign: "center",
        valign: "middle",
        align: "center",
        width: "70px",
        formatter: function (value, row, index) {
            return '<img style="width: 50px;height: auto" src="' + value + '" >';
        }
    }, {
        field: "price",
        title: "规格价",
        halign: "center",
        valign: "middle",
        align: "center",
        width: "70px",
        formatter: function (value, row, index) {
            return '<input class="price-input-' + row.id + ' form-control" type="text" value="' + value + '">';
        }
    }, {
        field: "inventory",
        title: "库存",
        halign: "center",
        valign: "middle",
        align: "center",
        width: "70px",
        formatter: function (value, row, index) {
            if (null == value) {
                return ""
            } else
            // return (value < 15 ? "<span style='color: red'>" : "<span>") + value + "</span>";
                return '<input class="inventory-input-' + row.id + ' form-control" style="' + (value < 15 ? 'color: red' : '') + '" type="text" value="' + value + '">';
        }
    }, {
        field: "gmtDatetime",
        title: "创建时间",
        align: "center",
        valign: "middle",
        halign: "center",
        width: "80px",
        sortable: true
    }, {
        field: "uptDatetime",
        title: "更新时间",
        align: "center",
        valign: "middle",
        halign: "center",
        width: "80px",
        sortable: true
    }, {
        title: "操作",
        halign: "center",
        valign: "middle",
        width: "150px",
        sortable: true,
        formatter: function (value, row, index) {
            var optHtml = "";
            optHtml += "<a class=\"btn btn-primary btn-xs\" href=\"javascript:;\" onclick=\"saveEdit(" + row.id + ")\"> 保存修改</a>\n";
            if(row.ifUniformSpec==1){
                optHtml += "<a class=\"btn btn-default btn-xs\" href=\"javascript:;\" onclick=\"editSku(" + row.id + ")\" data-toggle=\"modal\" data-target=\"#editModal\"> 修改图片</a>\n";
            }
            // optHtml += "<a class=\"btn btn-danger btn-xs\" href=\"javascript:;\" onclick=\"closeOrderBatch(" + row.id + ")\"> 关闭</a>\n";
            return optHtml;
        }
    }];

var queryParams = function (params) {
    console.log("params:", params);
    var param = {
        sku: {
            // orderStatus: orderStatus,
            // sourceType: sourceType
        },
        page: {
            offset: params.offset,
            current: params.offset / params.limit + 1,//bootstrap-table分页参数offset从0开始，计算的后端当前页参数current=(offset/limit+1)，
            size: params.limit,
            condition:{
                ifUniformSpec:curifUniformSpec
            }
        },
        searchText: params.search,
        intParam: sourceType,
        lzInventory: lzInventory,
        longParam:goodsId
    };

    return param;
}


//初始化表格 tableins:表格实例 ,
function initSkuTable(tableins) {
    tableins.bootstrapTable({
        columns: columns,
        method: "post",
        url: urlcore + "/api/sku/getSkuListAdmin",
        dataType: "json",
        queryParams: function (params) {
            return queryParams(params);
        },
        //返回数据预处理
        responseHandler: function (cbdata) {
            console.log(cbdata);
            if (null != cbdata.data && null != cbdata.data.records) {
                var records = cbdata.data.records;
                console.log(records);
                var res = {
                    //如果采用server端分页，必须有rows和total这两部分数据
                    "rows": records,
                    "total": cbdata.data.total
                };
                return res;
            } else return {"rows": [], "total": 0};
        },
        cache: false,
        uniqueId: "id",
        // toolbar: '#OrderListToolbar',//自定义工具栏，不同表格工具栏不同，一个jQuery 选择器，指明自定义的toolbar 例如:#toolbar, .toolbar.
        pagination: true,//启用分页条
        sidePagination: "server",//分页方式client或server
        // pageNumber: 1,
        pageSize: 16,//每页大小
        pageList: [16, 32, 48, 64],//可以选择每页大小
        showRefresh: true,//显示刷新
        sortable: true,//是否启用排序
        clickToSelect: true,//设置true 将在点击行时，自动选择rediobox 和 checkbox
        search: true,//默认为客户端搜索，服务器端接收params中的searchText后可以做服务器端搜索
        // searchText:"",//初始搜索文本
    });
}



//编辑商品信息和图片
function editSku(id) {
    curEditId = id;
//要先设置bootstrap-table中的uniqueId: "id",得到该行原始数据
    var originalData = $table.bootstrapTable('getRowByUniqueId', id);
    console.log(originalData);
    //主图
    $("#origThumbPicDiv").height(125);
    editThumbUrl = originalData.skuUrl;
    var origThumbPicHtml = "";
    origThumbPicHtml += "<div style='float: left'> <img class='oriImage' src=\"" + originalData.skuUrl + "\"></div>";
    $("#origThumbPic").html(origThumbPicHtml);
    modCount.modSumCount = 0;
}

//保存更改
function saveEditSku() {
    var modObject = new Object();
    var originalData = $table.bootstrapTable('getRowByUniqueId', curEditId);
    if (originalData.skuUrl != editThumbUrl) {
        modCount.modPicUrl = 1;
    }

    if (modCount.modPicUrl == 1) {
        modObject.skuUrl = editThumbUrl;
        modCount.modSumCount += 1;
    }

    //check modify
    if (modCount.modSumCount == 0)
        return;
    modifyPic();

    function modifyPic() {
        if (modCount.modSumCount > 0) {
            modObject.id = curEditId;
            //修改商品基本信息
            $.ajax({
                url: urlcore + "/api/sku/update",
                type: "post",
                dataType: "json",
                headers: {"Content-Type": "application/json;charset=UTF-8"},
                data: JSON.stringify(modObject),
                success: function (cbdata) {
                    console.log(cbdata.data);
                    alert("修改成功");
                    $table.bootstrapTable("refresh");
                    //移除模态框dropzone中旧图
                    goodsThumbDropzone.removeAllFiles(true);
                    $("#editModal input").val("");
                    modCount = {};
                    editThumbUrl = "";
                },
                error: function (cbdata) {
                    alert("更新状态失败");
                }
            });
        }
    }
}

//cancel edit
function cancelEditSku() {
    $("#editModal input").val("");
    goodsThumbDropzone.removeAllFiles(true);
    $("#origThumbPic").html("");
    editThumbUrl = "";
    modCount = {};
}


function saveEdit(id) {
    if (undefined == id || "" == id)
        return;
    var sku = new Object();
    var id = id;
    var skuPrice = $('input[class*="price-input-' + id + '"]').val();
    var skuInventory = $('input[class*="inventory-input-' + id + '"]').val();
    skuPrice=parseFloat(skuPrice);
    skuInventory=parseInt(skuInventory);
    if ("" == skuPrice || "" == skuInventory) {
        alert("价格和库存不能为空");
        return;
    }
    if(isNaN(skuPrice)||isNaN(skuInventory)){
        alert("价格和库存必须为数字");
        return;
    }
    sku = {
        id:id,
        price: skuPrice,
        inventory: skuInventory,
    };
    $.ajax({
        type: "POST",
        url: urlcore + "/api/sku/update",
        dataType: "json",
        contentType: "application/json;charset=UTF-8",
        data: JSON.stringify(sku),
        success: function (data) {
            alert("修改成功！");
            console.log("batchskudata", data);
            $table.bootstrapTable("refresh");
        },
        error: function () {

        }
    });


}

